<template>
  <div>
    <basic-container-one>
      <vue-element-loading :active="isActive" spinner="bar-fade-scale" color="#409eff" background-color="rgba(255,255,255,0.2)"/>
<div style="margin-top: 20px;"></div>
      <div style="z-index: 9999;position:absolute;right:3%;">
        <el-radio-group v-model="tabPositionThird" @change="handleClickThird">
          <el-radio-button label="userRoleAccount">创角数/创角用户</el-radio-button>
          <el-radio-button label="newRoleUserValueWithIMEICount">新创角用户/设备</el-radio-button>
          <el-radio-button label="tradeUserCount">充值人数/充值总额</el-radio-button>
        </el-radio-group>
      </div>
      <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
      <div id="main" style="margin-top: 0px; height:300px;width: 100%;position:relative">

      </div>
    </basic-container-one>
    <basic-container>
      <el-form :inline="true" :model="formInline" >
        <div style="margin-top: 22px">
          <el-form-item>
            <el-select v-model="formInline.gameTypeId" @change="selectType" clearable placeholder="平台名称">
              <el-option
                v-for="item in queryData.gameTypeList"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="formInline.projectId" @change="selectProject" filterable clearable placeholder="游戏">
              <el-option
                v-for="item in queryData.gameProjectList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="formInline.gameId" @change="selectGame" clearable placeholder="设备">
              <el-option
                v-for="item in queryData.gameList"
                :key="item.id"
                :label="item.gameName +'-'+ item.phoneName"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <!--          <el-form-item>-->
          <!--            <el-select v-model="formInline.serverId" @click.native="selectServer" clearable placeholder="区服名称">-->
          <!--              <el-option-->
          <!--                v-for="item in queryData.gameServerList"-->
          <!--                :key="item.serverNum"-->
          <!--                :label="item.serverName"-->
          <!--                :value="item.serverNum"/>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item v-show="level<=2">
            <el-select v-model="formInline.promoteGroupId" filterable clearable @change="selectPromoteGroup" placeholder="组长">
              <el-option
                v-for="item in queryData.promoteGroupList"
                :key="item.id"
                :label="item.account"
                :value="item.id"/>
            </el-select>
          </el-form-item>

          <el-form-item v-show="level <=3">
            <el-select v-model="formInline.promoteId" filterable clearable placeholder="推广员">
              <el-option
                v-for="item in queryData.promoteList"
                :key="item.id"
                :label="item.account"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item v-show="level <= 3">
            <el-checkbox v-model="checked">本账号推广</el-checkbox>
          </el-form-item>

          <el-form-item>
            <el-date-picker
              v-model="queryData.querDate"
              type="daterange"
              align="right"
              unlink-panels
              :clearable="false"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>


          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="queryFunc">查询</el-button>
            <el-button type="primary" icon="el-icon-download" @click="downloadReportFunc">下载</el-button>
          </el-form-item>
        </div>
      </el-form>

      <div style="margin-top: 20px">
        <el-table
          :data="dailyStatisticsList"
          show-summary
          stripe
          :summary-method="dailyStatisticsListSum"
          ref="el-table"
          style="width: 100%">
          <el-table-column
            prop="data"
            label="日期" key="0">
            <template slot-scope="scope">
              <span class="skucost-pruice">{{ scope.row.day | formatDate('YYYY-MM-DD') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userRoleAccount" label="创角数" key="1" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.userRoleAccount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userCount" label="创角用户" key="2" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.userCount }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="newRoleUserValueWithIMEICount" :render-header="renderHeader2" key="3" width="330"
                           label="新创角用户|新创角设备|新创角IP">
            <template slot-scope="scope">
              <span class="skucost-pruice">{{ scope.row.newRoleUserValueWithIMEICount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="actionUserCount" label="登录用户数" key="4" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.actionUserCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="tradeUserCount" label="充值人数" key="5" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.tradeUserCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="rechargeTimes" label="充值次数" key="6" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.rechargeTimes }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column prop="maxprice" label="充值总额" :render-header="renderHeader">-->
          <!--            <template slot-scope="scope">-->
          <!--              <span-->
          <!--                class="skucost-pruice">{{ scope.row.maxprice }}</span></span>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column prop="totalPrice" v-if="ischange"  width="150" label="充值总额"
                           key="7">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.totalPrice / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalZsPrice" v-if="ischange" :render-header="renderHeader3" width="180" label="实际充值总额"
                           key="7">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.directCharge / 100 + scope.row.goldPlatValue}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="directCharge" v-if="isshowtrue" key="8" label="现金充值" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.directCharge / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="isshowtrue" prop="goldPlatValue" key="9" label="通用币充值" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.goldPlatValue }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="isshowtrue" prop="num" key="10" label="绑定币充值" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">0</span>
            </template>
          </el-table-column>
          <el-table-column v-if="isshowtrue" prop="goldDiscountValue" key="11" label="折扣币充值"
                           :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.goldDiscountValue }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="isshowtrue" prop="voucherPrice" key="12" label="代金劵使用" :render-header="renderHeader">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.voucherPrice /100}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="block" style="margin-top: 20px;">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>

    </basic-container>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import * as echarts from 'echarts/core';
import {
  GridComponent
} from 'echarts/components';
import {
  LineChart
} from 'echarts/charts';
import {
  SVGRenderer
} from 'echarts/renderers';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/lib/component/legendScroll';
import tableHeaderTip from '@/components/game/tableHeaderTip';
import addbutton from '@/components/game/addbutton';

import {queryDailyStatistics} from '@/api/statistics/statistics'
import {getpromoterList} from '@/api/system/user'
import moment from "moment";
import {gameList, gamePhoneList, gameserverList, gameTypeList} from "@/api/game/game";
import user from "@/store/modules/user";
import {cloneObj, parseParam} from '@/util/util'
import {getToken} from "@/util/auth";
import VueElementLoading from 'vue-element-loading'
import '@/assets/myicon/iconfont.css'
echarts.use(
  [GridComponent, LineChart, SVGRenderer]
);

export default {
  name: "day",
  data() {
    return {
      isActive: false,
      level: user.state.promoteInfo.level,
      formInline: {
        gameTypeId: '',
        projectId: '',
        gameId: '',
        serverId: '',
        promoteGroupId: '',
        promoteId: '',
        startDate: 0,
        endDate: 0,
      },
      page: {
        current: 1,
        size: 10,
        total: 0,
      },
      queryData: {
        gameList: [],
        gameTypeList: [],
        gameServerList: [],
        gameProjectList: [],
        promoteGroupList: [],
        promoteList: [],
        querDate: [new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 6),new Date().getTime()],
      },
      dailyStatisticsList: [],
      date: '',
      checked: false,
      tabPositionThird: 'userRoleAccount',
      isshowtrue: false,
      ischange: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

    }

  },
  components: {
    addbutton,
    VueElementLoading
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  mounted() {
    this.initChart()
    this.initQueryDataList()
    this.queryDailyStatisticsFunc()
  },


  methods: {

    /**
     * 下载报表
     */
    downloadReportFunc() {

      let formData = cloneObj(this.formInline);
      if (this.checked) {
        formData.promoteId = user.state.userInfo.userId
      }
      formData.startDate = moment(this.queryData.querDate[0]).startOf('day').valueOf()
      formData.endDate = moment(this.queryData.querDate[1]).endOf('day').valueOf()
      window.location.href = `/api/blade-statistic/statistics/queryDailyStatisticsReport?${parseParam(formData)}&blade-auth=${getToken()}`
    },


    /**
     * 搜索条件初始化
     */
    initQueryDataList() {
      this.isActive = true
      if (this.level === 2) {
        this.getPromoteGroupList(user.state.userInfo.userId)
      } else if (this.level === 3) {
        this.getPromoteList(user.state.userInfo.userId)
      }
      this.gameTypeList()
      this.getProjectList()
      this.getGameList()
    },

    /**
     * 搜索按钮
     */
    queryFunc() {
      this.refreshTable()
    },

    dailyStatisticsListSum(param) {

      const {columns, data} = param;

      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => item[column.property]);
        if (values.length != 0) {
          if (column.property === 'newRoleUserValueWithIMEICount') {
            sums[index] = values.reduce((prev, curr) => {
              if (prev === 0) {
                return curr
              }
              let prevArr = prev.split("|")
              let currArr = curr.split("|")
              return (Number(prevArr[0]) + Number(currArr[0])) + "|"
                + (Number(prevArr[1]) + Number(currArr[1])) + "|" + (Number(prevArr[2]) + Number(currArr[2]))
            })
          } else {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            })

          }
        }

        if (sums[index] === 0) {
          sums[index] = "--"
        } else if(index == 8) {
          let sumE = 0;
          for(let i = 0; i < this.dailyStatisticsList.length; i++) {
            sumE += this.dailyStatisticsList[i].directCharge / 100 + this.dailyStatisticsList[i].goldPlatValue
          }
          sums[8] = sumE;
        } else if (column.property === "totalPrice" || column.property === "directCharge" || column.property === "voucherPrice") {
          sums[index] = sums[index] / 100
        }
      });

      return sums;
    },

    refreshTable() {
      this.isActive = true
      this.queryDailyStatisticsFunc()
    },

    queryDailyStatisticsFunc() {
      let formData = cloneObj(this.formInline);
      if (this.checked) {
        formData.promoteId = user.state.userInfo.userId
      }
      formData.startDate = moment(this.queryData.querDate[0]).startOf('day').valueOf()
      formData.endDate = moment(this.queryData.querDate[1]).endOf('day').valueOf()
      queryDailyStatistics(formData, this.page.current, this.page.size).then(res => {
        this.isActive = false
        let data = res.data.data
        this.dailyStatisticsList = data.records
        this.page.total = data.total
        this.handleClickThird(this.tabPositionThird)
      })
    },

    fatherMethod() {
      this.isshowtrue ? this.isshowtrue = false : this.isshowtrue = true;
      this.ischange = false;
      this.$nextTick(() => {

        this.ischange = true;
        this.$refs['el-table'].doLayout();
      })

    },
    renderHeader2(h, {column}) {
      return h(  // 创建元素
        'div', [
          h('span', column.label),  // label标题文案
          h(tableHeaderTip, {  // tooltips组件
            props: {
              messages: ['新创角用户：当日(24小时),首次创建角色的用户数;', '新创角设备：当日(24小时),首次创建角色设备总数(去重);', '新创角设备：当日(24小时),首次创建角色设备总数(去重);'],
            }
          })
        ]
      )
    },

    renderHeader3(h, {column}) {
      return h(  // 创建元素
        'div', [
          h('span', column.label),  // label标题文案
          h(addbutton, {  // tooltips组件
            props: {
              messages: ['实际充值总额'],
              isshowtrue: this.isshowtrue,
            }
          })
        ]
      )
    },
    handleSizeChange(val) {
      this.page.size = val
      this.refreshTable()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.refreshTable()
    },
    handleClickThird(tab) {
       console.log("tab",tab)
      let xdata = this.dailyStatisticsList.map(d => moment(d.day).format('YYYY-MM-DD'))
      let ydata = []
      switch (tab) {
        case 'userRoleAccount':
          ydata.push(this.dailyStatisticsList.map(d => d.userRoleAccount))
          ydata.push(this.dailyStatisticsList.map(d => d.userCount))
          this.setChartsData("创角数", "创角用户", xdata, ydata)
          break;
        case 'newRoleUserValueWithIMEICount':
          ydata.push(this.dailyStatisticsList.map(d => d.newRoleUserValue))
          ydata.push(this.dailyStatisticsList.map(d => d.imeiCount))
          this.setChartsData("新创角用户", "新创角设备", xdata, ydata)
          break;
        case 'tradeUserCount':
          ydata.push(this.dailyStatisticsList.map(d => d.tradeUserCount))
          ydata.push(this.dailyStatisticsList.map(d => d.totalPrice / 100))
          this.setChartsData("充值人数", "充值总额", xdata, ydata)
          break;
      }

    },
    renderHeader(h, {column}) {
      let label = column.label
      let txtmap = {
        '创角数': '创角数：当日(24小时),成功创建角色数量(唯一,含滚服用户)',
        '创角用户': '创角用户：当日(24小时),成功创角的用户数(去重,含滚服用户)',
        '新创角用户|新创角设备|新创角IP': '新创角用户：当日(24小时),首次创建角色的用户数;' +
          '新创角设备：当日(24小时),首次创建角色设备总数(去重);' +
          '新创角IP：当日(24小时),首次创建角色IP总数(去重);',
        '登录用户数': '登录用户数：当日(24小时),登录的用户数(去重)',
        '充值人数': '充值人数：当日(24小时),在游戏内充值成功的订单的用户数(去重)',
        '充值次数': '充值次数：当日(24小时),在游戏内充值成功的订单数量',
        '充值总额': '充值总额：当日(24小时),在游戏内充值成功的订单金额总和',
        '现金充值': '现金充值：当日(24小时),在游戏内充值成功的订单,使用现金支付金额总和',
        '通用币充值': '通用币充值：当日(24小时),在游戏内充值成功的订单,使用通用币支付金额总和',
        '绑定币充值': '绑定币充值：当日(24小时),在游戏内充值成功的订单,使用绑定币支付金额总和',
        '折扣币充值': '折扣币充值：当日(24小时),在游戏内充值成功的订单,使用折扣币支付金额总和,该部分不参与结算',
        '代金劵使用': '代金劵使用：当日(24小时),在游戏内充值成功的订单,使用代金券金额总和,该部分不参与结算',
      }
      return h('span', {}, [
        h('span', {}, label),
        h('el-popover', {
          props: {
            placement: 'top-start', 'data-html': 'true', trigger: 'hover', content: (function () {
              return txtmap[label];
            })()
          }
        }, [
          h('i', {slot: 'reference', class: 'iconfont el-third-iconwenhao',style:'margin-left:2px' }, '')
        ]),

      ])
    },

    initChart() {
      this.charts = echarts.init(document.getElementById('main'));
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        this.charts.resize();
      });
    },

    setChartsData(name1, name2, xdata, ydata) {

      this.charts.clear()

      const option = {
        tooltip: {
          trigger: 'axis',
          confine: true, //将 tooltip 框限制在图表的区域内，在移动端开发时非常有用
          // extraCssText: 'background:rgba(0,0,0);border:0;color:rgba(225,225,225);',

        },
        title: {
          text: "每日概况",
          textStyle: { //主标题文本样式{"fontSize": 18,"fontWeight": "bolder","color": "#333"}
            fontSize: 18,
            color: '#666666',
            fontStyle: 'normal',
            fontWeight: 'normal',
          },
          x: '3%', //水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
          y: '3%', //垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        legend: {
          orient: 'horizontal',
          x: '15%', //水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
          y: '3%', //垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
          textStyle: { //主标题文本样式{"fontSize": 18,"fontWeight": "bolder","color": "#333"}
            fontSize: 15,
            color: '#666666',
            fontStyle: 'normal',
            fontWeight: 'normal',
          },
          data: [name1, name2]
        },
        grid: { //调整图表上下左右位置
          top: '20%',
          left: '2%',
          right: '2%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xdata,
          boundaryGap: false // 不留白，从原点开始
        },
        yAxis: {
          type: 'value',
          axisPointer: {
            type: 'cross',
            label: {
              // backgroundColor: '#6a7985'
            }
          }
        },
        series: [
          {
            name: name1,
            data: ydata[0],
            type: 'line',
            symbol: "none",

            lineStyle: {
              width: 1//设置线条粗细
            },
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(58,77,233,0.3)'
              }, {
                offset: 1,
                color: 'rgba(58,77,233,0.1)'
              }])
            },
          },
          {
            name: name2,
            data: ydata[1],
            type: 'line',
            symbol: "none",
            lineStyle: {
              width: 1//设置线条粗细
            },
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(137,189,27,0.3)'
              }, {
                offset: 1,
                color: 'rgba(137,189,27,0.1)'
              }])
            },
          }]
      };

      this.charts.setOption(option);

    },


    selectType() {
      this.formInline.projectId = ''
      this.formInline.gameId = ''
      this.formInline.serverId = ''
      this.getProjectList()
      this.getGameList()
    },

    selectProject() {
      this.formInline.gameId = ''
      this.formInline.serverId = ''
      this.getGameList()
    },
    selectGame() {
      this.formInline.serverId = ''
    },

    selectServer() {
      if (this.formInline.gameId !== '' || this.formInline.projectId !== '') {
        this.getGameServerList()
      } else {
        this.queryData.gameServerList = []
        this.$message({
          type: "error",
          message: "请先选择游戏"
        });
      }
    },

    selectPromoteGroup(value) {
      this.formInline.promoteId = ''
      if (value === '') {
        this.queryData.promoteList = []
        return
      }
      this.getPromoteList(this.formInline.promoteGroupId)
    },


    getPromoteGroupList(pid) {
      getpromoterList({"userPid": pid, "level": 3}).then(res => {
        this.queryData.promoteGroupList = res.data.data;
      });
    },

    getPromoteList(pid) {
      getpromoterList({"userPid": pid, "level": 4}).then(res => {
        this.queryData.promoteList = res.data.data
      });
    },

    getGameServerList() {
      gameserverList(this.formInline).then(res => {
        this.queryData.gameServerList = res.data.data
      });
    },
    getGameList() {
      gamePhoneList(this.formInline).then(res => {
        this.queryData.gameList = res.data.data
      });
    },
    getProjectList() {
      gameList({"typeId": this.formInline.gameTypeId}).then(res => {
        this.queryData.gameProjectList = res.data.data
      });
    },

    gameTypeList() {
      gameTypeList().then(res => {
        this.queryData.gameTypeList = res.data.data
      });

    },
  }
}
</script>

